package com.bankcomm.ui.specialwidget;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import com.bankcomm.R;
import com.bankcomm.common.ConfigManager;
import com.bankcomm.common.LPMid;
import com.bankcomm.ui.EMPView;
import com.rytong.tools.crypto.AESCipher;
import com.rytong.tools.httpconnect.WaitDialog;
import com.rytong.tools.ui.Component;
import com.rytong.tools.ui.WaitProgressDialog;
import com.rytong.tools.utils.Utils;

public class LPWebView extends Component {
	Activity mainAct;

	public class MyLPWebView extends LinearLayout implements
			CompositedComponent, OnClickListener {

		private WebView myWebView;
		private WebSettings mySettings;
		private ImageButton btnReture;// 返回
		private ImageButton btnBack;// 返回
		private ImageButton btnForward;// 向前
		private ImageButton btnRefresh;// 刷新
		private WaitProgressDialog dialog;

		public MyLPWebView(Context context) {
			super(context);
			initView();
		}

		private void initView() {
			LayoutInflater.from(mainAct).inflate(R.layout.bcm_webview_widget,
					this);
			myWebView = (WebView) findViewById(R.id.webView);
			myWebView.requestFocus();
			String url = getPropertyByName("url").trim();
			myWebView.loadUrl(url);
			// myWebView.loadUrl("file:/android_asset/Noname.html");
			myWebView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
			myWebView.addJavascriptInterface(new JavaScriptInterFaceUtils(),
					"bocm_pay");
			setConfig();
			btnReture = (ImageButton) findViewById(R.id.return_btn);
			btnBack = (ImageButton) findViewById(R.id.back_btn);
			btnForward = (ImageButton) findViewById(R.id.forward_btn);
			btnRefresh = (ImageButton) findViewById(R.id.refresh_btn);
			btnReture.setOnClickListener(this);
			btnBack.setOnClickListener(this);
			btnForward.setOnClickListener(this);
			btnRefresh.setOnClickListener(this);
			myWebView.setWebViewClient(client);
			myWebView.setWebChromeClient(chromeClient);
//			dialog = new WaitProgressDialog(mainAct, mainAct
//					.getString(R.string.onMapLoading));
//			dialog.show(null);

		}

		WebViewClient client = new WebViewClient() {
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				view.loadUrl(url);
				Utils.printOutToConsole("webview==="+url);
				return true;
			}

			public void onPageFinished(WebView view, String url) {
				super.onPageFinished(view, url);
//				dialog.dismiss();
			}

			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				super.onPageStarted(view, url, favicon);
			}

			public void onReceivedError(WebView view, int errorCode,
					String description, String failingUrl) {
//				dialog.dismiss();
			}

			public void onReceivedSslError(WebView view,
					android.webkit.SslErrorHandler handler,
					android.net.http.SslError error) {
				handler.proceed();
			};
		};

		WebChromeClient chromeClient = new WebChromeClient() {

			@Override
			public boolean onJsAlert(WebView view, String url, String message,
					final JsResult result) {
				// TODO Auto-generated method stub
				// js: alert();
				new AlertDialog.Builder(getContext()).setTitle("提示").setMessage(
						message).setCancelable(false).setPositiveButton(
						android.R.string.ok, new AlertDialog.OnClickListener() {

							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub
								result.confirm();
							}

						}).show();
				return true;
			}

			@Override
			public boolean onJsConfirm(WebView view, String url,
					String message, final JsResult result) {
				// TODO Auto-generated method stub
				// js: window.confirm();
				new AlertDialog.Builder(getContext()).setTitle("提示").setMessage(
						message).setCancelable(false).setPositiveButton(
						android.R.string.ok, new AlertDialog.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub
								result.confirm();
							}

						}).setNegativeButton(android.R.string.cancel,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub
								result.cancel();
							}
						}).show();
				return true;
			}

		};

		protected void setConfig() {
			mySettings = myWebView.getSettings();
			mySettings.setSupportZoom(true);
			mySettings.setJavaScriptEnabled(true);
			mySettings.setBuiltInZoomControls(true);
			mySettings.setLoadsImagesAutomatically(true);
			mySettings.setAppCacheEnabled(false);
			mySettings.setJavaScriptCanOpenWindowsAutomatically(true);
			myWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
		}

		@Override
		public Component composited() {
			return LPWebView.this;
		}

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.return_btn:
				handlerBackPress();
				break;
			case R.id.back_btn:
				if (myWebView.canGoBack()) {
					myWebView.goBack();
				}
				break;
			case R.id.forward_btn:
				if (myWebView.canGoForward()) {
					myWebView.goForward();
				}
				break;
			case R.id.refresh_btn:
				myWebView.reload();
				break;
			}

		}

		public void handlerBackPress() {
			if (myWebView.canGoBack()) {
				myWebView.goBack();
			} else {
				myWebView.stopLoading();
			}
		}
	}

	@Override
	public void initRealView(final Activity activity, String value) {
		// TODO Auto-generated method stub
		mainAct = activity;
		realView_ = new MyLPWebView(activity);

	}

	public void mouldH() throws Exception {
		super.mouldH();
	}

	class JavaScriptInterFaceUtils {
		
		String finalBody = "";
		String PAY_URL = ConfigManager.SERVER_URI
				+ ConfigManager.PAYMENT_INTER_URL;

		public void bocmB2C4Pay(String body) {
			if (body != null) {
//				System.out.println(body);
				finalBody = body;

				LPMid.getInstance().waitDialog_.addFgTask(mainAct,null, 0, 0, 0, new WaitDialog.Task(0) {
					String reply = "";

					@Override
					public void run(WaitDialog dlg) throws Exception {
						 finalBody=AESCipher.encrypt(finalBody,AESCipher.clientKey_,
						 AESCipher.clientIv_);
//						 System.out.println(finalBody);
						 reply = (String) LPMid.getInstance().hm_
								.sendPostRequest(PAY_URL, finalBody, this,
										null, null);
					}

					@Override
					public void onFailure(WaitDialog dlg) {
						super.onFailure(dlg);
						((EMPView) mainAct).handleException(getErrMsg());
					}

					@Override
					public void onSuccess(WaitDialog dlg) {
						super.onSuccess(dlg);
						Utils.printOutToConsole(reply);
						try {
							reply=AESCipher.decrypt(reply, AESCipher.serverKey_,AESCipher.serverIv_);
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						mainAct.runOnUiThread(new Runnable() {
							
							@Override
							public void run() {
								// TODO Auto-generated method stub
								((EMPView) mainAct).parserXMLToView(reply);
								
							}
						});
					}

				});
			}
		}
	}

}
